package com.plantpoint.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plantpoint.dao.UserDao;
import com.plantpoint.entity.dto.OpenIdAndSessionKey;
import com.plantpoint.entity.dto.UserLoginDTO;
import com.plantpoint.entity.pojo.User;
import com.plantpoint.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Set;

/***
 * @date   2021/4/20 0020 19:44
 * @author JackeyTower
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> {
    private WechatUtil wechatUtil;
    private IdWorker idWorker;
    private RedisUtil redisUtil;
    private UserDao userDao;
    private JwtUtil jwtUtil;

    public UserServiceImpl(WechatUtil wechatUtil, IdWorker idWorker, RedisUtil redisUtil, UserDao userDao, JwtUtil jwtUtil) {
        this.wechatUtil = wechatUtil;
        this.idWorker = idWorker;
        this.redisUtil = redisUtil;
        this.userDao = userDao;
        this.jwtUtil = jwtUtil;
    }

    //传入code,rawData,signature，接收token
    public String login(UserLoginDTO userLoginDTO) {
        //已接收到从客户端获取的code
        String code = userLoginDTO.getCode();

        //开发者服务器 登录凭证校验接口 appid + appsecret + code
        JSONObject SessionKeyOpenId = wechatUtil.getSessionKeyAndOpenId(code);
        System.out.println("SessionKeyOpenId:"+SessionKeyOpenId);

        //获取keySet,先判断是否存在错误码
        Set<String> keySet = SessionKeyOpenId.keySet();
        if (keySet.contains("errcode")) {
            //获取错误码
            String errcode = SessionKeyOpenId.getString("errcode");
            if (errcode.equals("40029")) {
                return "error:40029";
            }
            else if (errcode.equals("40163")){
                return "error:40163";
            }
        }
        //如无出错，继续执行
        String openid = SessionKeyOpenId.getString("openid");
        String session_key = SessionKeyOpenId.getString("session_key");

        //生成一个唯一skey，用于维护微信小程序用户与服务端的会话。
        String skey = idWorker.nextId() + "";
        //skey为key，openid和session_key封装成的新对象作为value，存入缓存
        OpenIdAndSessionKey openIdAndSessionKey = new OpenIdAndSessionKey(openid, session_key);
        redisUtil.set(skey, openIdAndSessionKey);

        // 根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = userDao.selectOne(wrapper.eq("openid", openid));
        if (user == null) {
            User newUser = new User();
            BeanUtils.copyProperties(userLoginDTO.getUserInfo(), newUser);
            newUser.setOpenid(openid);
            newUser.setRole(0);
            newUser.setCreateTime(DateTimeTransferUtil.getNowTimeStamp());
            newUser.setLastVisitTime(DateTimeTransferUtil.getNowTimeStamp());
            userDao.insert(newUser);
        } else {
            //老用户，更新登陆时间
            user.setLastVisitTime(DateTimeTransferUtil.getNowTimeStamp());
            userDao.updateById(user);
        }
        return jwtUtil.createJWTbySkey(skey);
    }
}
